package com.guoji.cameracall.client

import android.graphics.Point
import android.hardware.Camera
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.guoji.cameracall.databinding.ActivityCallClientBinding
import com.guoji.cameracall.helper.DecodeLiveH265
import com.guoji.cameracall.helper.EncodePushH265
import com.guoji.cameracall.socket.SocketLiveClient
import java.lang.Exception
import java.net.URI

/**
 * create by zhongZihao on 2021/9/24
 */
class VideoCallClientActivity : AppCompatActivity(), SurfaceHolder.Callback {
    private lateinit var binding: ActivityCallClientBinding
    private var decoder: DecodeLiveH265? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCallClientBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initSurface()

        binding.btCall.setOnClickListener {
            //开始连接到远程设备，并编码自己摄像头数据
            val ip = binding.etPullIp.text.toString()
            val port = binding.etPullPort.text.toString()
            val uri = URI.create("ws://$ip:$port")
            val socketLiveClient = SocketLiveClient(uri)
            socketLiveClient.setDataCallback {
                //解码远程设备的帧
                decoder?.callback(it)
            }
            socketLiveClient.start()
            binding.cameraSurface.startEncoder(socketLiveClient)
        }

        binding.btTakePhoto.setOnClickListener {
            binding.cameraSurface.startCaptrue()
            Toast.makeText(this, "拍照成功", Toast.LENGTH_SHORT).show()
        }
    }


    private fun initSurface() {
        binding.remoteSurface.holder.addCallback(this)
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        decoder = DecodeLiveH265()
        decoder!!.initDecoder(holder.surface)
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {

    }


    override fun onDestroy() {
        super.onDestroy()
        decoder?.release()
    }

}